import { defineComponent, Fragment, ref, watch } from 'vue'
import { ElTree as Tree, ElButton as Button } from 'element-plus'
import { uid } from '@formily/shared'
import { observer } from '@formily/reactive-vue'
import { usePrefix, IconWidget, TextWidget } from '@pg/prototypes'
import { Title } from './Title'
import { Header } from './Header'
import { traverseTree } from './shared'
import { ITreeDataSource, INodeItem } from './types'
import { GlobalRegistry } from '@designable/core'
import './styles.less'

const limitTreeDrag = ({ dropPosition }) => {
  if (dropPosition === 0) {
    return false
  }
  return true
}

export interface ITreePanelProps {
  treeDataSource: ITreeDataSource
  allowTree: boolean
  defaultOptionValue: {
    label: string
    value: any
  }[]
}

export const TreePanel = observer(
  defineComponent({
    props: ['modelValue', 'defaultOptionValue', 'allowTree', 'selectItem'],
    setup(props, {emit}) {
      const prefix = usePrefix('data-source-setter')
      const treeData = ref(props.modelValue || [])
      const current = ref()
      watch(() => props.modelValue, newVal => {
        treeData.value = newVal || []
      })
      watch(() => props.selectItem, newVal => {
        // console.log(newVal)
      })
      const addNode = () => {
        const uuid = uid()
        const initialKeyValuePairs = props.defaultOptionValue?.map(
          (item) => ({ ...item })
        ) || [
          {
            label: 'label',
            value: `${GlobalRegistry.getDesignerMessage(`SettingComponents.DataSourceSetter.item`)} ${treeData.value.length + 1}`,
          },
          { label: 'value', value: uuid },
        ]
        return {
          key: uuid,
          duplicateKey: uuid,
          label: `${GlobalRegistry.getDesignerMessage(`SettingComponents.DataSourceSetter.item`)} ${treeData.value.length + 1}`,
          map: initialKeyValuePairs,
          children: [],
        }
      }
      const handlerAddRootNode = () => {
        treeData.value = treeData.value.concat(addNode())
      }
      const handlerAddChildNode = (parentNode) => {
        if (parentNode) {
          parentNode.children = parentNode.children.concat(addNode())
        }
      }
      return () => (
        <Fragment>
          <Header
            title={
              <TextWidget token="SettingComponents.DataSourceSetter.dataSourceTree" />
            }
            extra={
              <div>
                <Button
                  link={true}
                  onClick={handlerAddRootNode}
                  icon={<IconWidget infer="Add" />}
                >
                  <TextWidget token="SettingComponents.DataSourceSetter.addNode" />
                </Button>
                <Button
                  link={true}
                  disabled={current.value == null}
                  onClick={() => handlerAddChildNode(current.value)}
                  icon={<IconWidget infer="Add" />}
                >
                  <TextWidget token="SettingComponents.DataSourceSetter.addChildNode" />
                </Button>
              </div>
            }
          />
          <div className={`${prefix.value + '-layout-item-content'}`}>
            <Tree
              draggable={true}
              allowDrop={props.allowTree ? () => true : limitTreeDrag}
              defaultExpandAll
              autoExpandParent
              data={treeData.value}
              v-slots={{
                default: ({data}) => {
                  return (
                    <Title value={data} prop={"label"} onRemove={() => {
                      const idx = treeData.value.findIndex(item => item.key === data.key)
                      if (idx > -1) {
                        treeData.value.splice(idx, 1)
                      }
                    }}></Title>
                  )
                }
              }}
              onCurrentChange={(data) => {
                current.value = data
                emit('update:selectItem', data)
              }}
            ></Tree>
          </div>
        </Fragment>
      )
    }
  })
)
